/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.rpc;

import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.AbstractUpgradeModulePackageRpcServiceImpl;
import com.je.common.base.service.rpc.UpgradeModulePackageRpcService;
import com.je.common.base.upgrade.PackageResult;
import com.je.common.base.upgrade.UpgradeResourceEnum;
import com.je.common.base.util.JEUUID;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.rpc.upgrade.UpgradelogRpcService;
import org.apache.servicecomb.provider.pojo.RpcSchema;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RpcSchema(schemaId = "upgradeModulePackageRpcService")
public class UpgradeModulePackageRpcServiceImpl extends AbstractUpgradeModulePackageRpcServiceImpl implements UpgradeModulePackageRpcService {

    @Autowired
    private MetaService metaService;

    @Autowired
    private UpgradelogRpcService upgradelogRpcService;

    @Autowired
    private PermissionRpcService permissionRpcService;

    @Override
    public String doCheck(PackageResult packageResult) {
        return null;
    }

    @Override
    public PackageResult packageModule(DynaBean upgradeBean) {
        PackageResult packageResult = new PackageResult();

        List<String> roleIdList = upgradeBean.get("roleIdList") == null ? new ArrayList<>() : (List<String>) upgradeBean.get("roleIdList");
        List<String> topMenuIdList = upgradeBean.get("topMenuIdList") == null ? new ArrayList<>() : (List<String>) upgradeBean.get("topMenuIdList");
        List<String> menuIdList = upgradeBean.get("menuIdList") == null ? new ArrayList<>() : (List<String>) upgradeBean.get("menuIdList");

        packageResult.setProductRoles(packageRoles(roleIdList));
        packageResult.setProductMenus(packageMenu(menuIdList));
        packageResult.setProductTopMenus(packageTopMenu(topMenuIdList));
        return packageResult;
    }

    @Override
    public String installModule(PackageResult packageResult) {
        //菜单
        if(packageResult.getProductMenus()!=null){
            installMenu(packageResult.getInstallPackageId(),packageResult.getProductMenus());
        }
        //顶部菜单
        if(packageResult.getProductTopMenus()!=null){
            installTopMenu(packageResult.getInstallPackageId(),packageResult.getProductTopMenus());
        }
        //角色
        if(packageResult.getProductRoles()!=null){
            installRoles(packageResult.getInstallPackageId(),packageResult.getProductRoles());
        }

        return null;
    }

    private String installMenu(String installPackageId,List<DynaBean> menuBeanList) {
        for(DynaBean dynaBean :menuBeanList){
            String pkValue = dynaBean.getStr("JE_CORE_MENU_ID");
            DynaBean menu = metaService.selectOneByPk("JE_CORE_MENU",pkValue);
            dynaBean.table("JE_CORE_MENU");
            dynaBean.setStr("MENU_LINK_TOPMENU_NAME",null);
            dynaBean.setStr("MENU_LINK_TOPMENU_ID",null);
            if(menu!=null){
                commonService.buildModelModifyInfo(dynaBean);
                metaService.update(dynaBean,ConditionsWrapper.builder().eq("JE_CORE_MENU_ID",pkValue));
                //授权
                try{
                    permissionRpcService.quickGrantMenu(dynaBean.getStr("SY_PRODUCT_ID"),dynaBean.getStr("JE_CORE_MENU_ID"));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else{
                commonService.buildModelCreateInfo(dynaBean);
                metaService.insert(dynaBean);
                //授权
                try{
                    permissionRpcService.quickGrantMenu(dynaBean.getStr("SY_PRODUCT_ID"),pkValue);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            //目录
            /*List<Map<String,Object>> parentInfos = (List<Map<String, Object>>) dynaBean.get("parentList");
            insertOrUpdate(parentInfos,"JE_CORE_MENU","JE_CORE_MENU_ID");*/

            //记录升级日志
            upgradelogRpcService.saveUpgradelog(installPackageId,
                    UpgradeResourceEnum.MENU.getCode(),UpgradeResourceEnum.MENU.getName(),
                    dynaBean.getStr("MENU_MENUNAME"),"");
        }
        return null;
    }

    private String installTopMenu(String installPackageId,List<DynaBean> topMenuBeanList) {
        for(DynaBean dynaBean :topMenuBeanList){
            String pkValue = dynaBean.getStr("JE_RBAC_HEADMENU_ID");
            DynaBean menu = metaService.selectOneByPk("JE_RBAC_HEADMENU",pkValue);
            dynaBean.table("JE_RBAC_HEADMENU");
            if(menu!=null){
                metaService.delete("JE_RBAC_HEADMENU",ConditionsWrapper.builder().eq("JE_RBAC_HEADMENU_ID",pkValue));
                metaService.delete("JE_RBAC_HEADMENU_RELATION",ConditionsWrapper.builder().eq("JE_RBAC_HEADMENU_ID",pkValue));
            }
            commonService.buildModelCreateInfo(dynaBean);
            metaService.insert(dynaBean);
            //关联菜单模块,不用管
            /*List<Map<String,Object>> headmenuRelationList = (List<Map<String,Object>>) dynaBean.get("headmenuRelation");
            if(headmenuRelationList!=null&&headmenuRelationList.size()>0){
                batchInsert(headmenuRelationList,"JE_RBAC_HEADMENU_RELATION");
            }*/
            //记录升级日志
            upgradelogRpcService.saveUpgradelog(installPackageId,
                    UpgradeResourceEnum.TOPMENU.getCode(),UpgradeResourceEnum.TOPMENU.getName(),
                    dynaBean.getStr("HEADMENU_NAME"),dynaBean.getStr("HEADMENU_CODE"));
        }
        return null;
    }




    private String installRoles(String installPackageId,List<DynaBean> roleBeanList) {
        for(DynaBean dynaBean :roleBeanList){
            String pkValue = dynaBean.getStr("JE_RBAC_ROLE_ID");
            DynaBean menu = metaService.selectOneByPk("JE_RBAC_ROLE",pkValue);
            dynaBean.table("JE_RBAC_ROLE");
            if(menu!=null){
                commonService.buildModelModifyInfo(dynaBean);
                dynaBean.setStr("ROLE_PERMGROUP_ID",null);
                dynaBean.setStr("ROLE_PERMGROUP_NAME",null);
                metaService.update(dynaBean,ConditionsWrapper.builder().eq("JE_RBAC_ROLE_ID",pkValue));
            }else{
                commonService.buildModelCreateInfo(dynaBean);
                dynaBean.setStr("ROLE_PERMGROUP_ID",null);
                dynaBean.setStr("ROLE_PERMGROUP_NAME",null);
                metaService.insert(dynaBean);
            }
            //目录
            List<Map<String,Object>> parentInfos = (List<Map<String, Object>>) dynaBean.get("parentList");
            insertOrUpdate(parentInfos,"JE_RBAC_ROLE","JE_RBAC_ROLE_ID");
            //记录升级日志
            upgradelogRpcService.saveUpgradelog(installPackageId,
                    UpgradeResourceEnum.ROLE.getCode(),UpgradeResourceEnum.ROLE.getName(),
                    dynaBean.getStr("ROLE_NAME"),dynaBean.getStr("ROLE_CODE"));

        }
        return null;
    }

    private List<DynaBean> packageMenu(List<String> menuIds) {
        List<DynaBean> menuBeanList = metaService.select("JE_CORE_MENU", ConditionsWrapper.builder()
                .in("JE_CORE_MENU_ID",menuIds));
        List<String> allParentIds  =new ArrayList<>();
        for(DynaBean dynaBean:menuBeanList){
            List<String> currentParentIds = new ArrayList<>();
            String SY_PARENTPATH = dynaBean.getStr("SY_PARENTPATH");
            for(String id:SY_PARENTPATH.split("/")){
                if(!"ROOT".equals(id)&&!allParentIds.contains(id)){
                    allParentIds.add(id);
                    currentParentIds.add(id);
                }
            }
            dynaBean.set("parentList",metaService.select("JE_CORE_MENU",ConditionsWrapper.builder().in("JE_CORE_MENU_ID",currentParentIds)));
        }
        return sort(menuBeanList);
    }

    private List<DynaBean> packageTopMenu(List<String> topMenuIds) {
        List<DynaBean> menuBeanList = metaService.select("JE_RBAC_HEADMENU",ConditionsWrapper.builder()
                .in("JE_RBAC_HEADMENU_ID",topMenuIds));
        //关联菜单模块，不用管
       /* for(DynaBean dynaBean:menuBeanList){
           String menuid = dynaBean.getStr("JE_RBAC_HEADMENU_ID");
           List<DynaBean> list = metaService.select("JE_RBAC_HEADMENU_RELATION",ConditionsWrapper.builder().eq("JE_RBAC_HEADMENU_ID",menuid));
           dynaBean.set("headmenuRelation",list);
        }*/
        return menuBeanList;
    }

    private List<DynaBean> packageRoles(List<String> roleIds) {
        List<DynaBean> roleBeanList = metaService.select("JE_RBAC_ROLE",ConditionsWrapper.builder()
                .in("JE_RBAC_ROLE_ID",roleIds));
        List<String> allParentIds  =new ArrayList<>();
        for(DynaBean dynaBean:roleBeanList){
            List<String> currentParentIds = new ArrayList<>();
            String SY_PARENTPATH = dynaBean.getStr("SY_PARENTPATH");
            for(String id:SY_PARENTPATH.split("/")){
                if(!"ROOT".equals(id)&&!allParentIds.contains(id)){
                    allParentIds.add(id);
                    currentParentIds.add(id);
                }
            }
            dynaBean.set("parentList",metaService.select("JE_RBAC_ROLE",ConditionsWrapper.builder().in("JE_RBAC_ROLE_ID",currentParentIds)));
        }
        return sort(roleBeanList);
    }

}
